﻿using SuperX.Common.Log;
using SuperX.SuperSocket.Socket.Transfer.Client;
using SuperX.SuperSocket.Socket.Transfer.Client.DownLoad;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace SuperX.SuperSocket.Socket.Transfer.Client.DownLoad.Command
{
    internal class DoData : DownloadCommandBase
    {
        public override string Name
        {
            get
            {
                return UpLoadOP.DoData.ToString();
            }
        }

        public override void ExecuteCommand(DownLoadEngine session, TransferCommandInfo commandInfo)
        {
            ConsoleLogHelper.Debug("DoData");
            try
            {
                if (session.m_fileStream != null)
                {
                    lock (session.lockobj)
                    {
                        session.m_fileStream.Write(commandInfo.Data, 0, commandInfo.Data.Length);
                        session.DownloadInfo.TransferedLength += commandInfo.Data.Length;
                        session.OnTransferStep(
                            session.DownloadInfo.TransferLength,
                            session.DownloadInfo.TransferedLength,
                            commandInfo.Data.Length);
                        ConsoleLogHelper.Debug($"{session.DownloadInfo.TransferLength} / {session.DownloadInfo.TransferedLength} " +
                            $"{((double)session.DownloadInfo.TransferedLength / session.DownloadInfo.TransferLength).ToString("P2")}");
                        if (session.DownloadInfo.TransferLength <= session.DownloadInfo.TransferedLength)
                        {
                            ConsoleLogHelper.Debug("DoEnd");
                            session.SendData(UpLoadOP.DoEnd, new byte[] { 1 }, 0, 1);
                            Task.Factory.StartNew(() =>
                            {
                                //session.m_EndEvent.WaitOne(5000);
                                session.DoDownloadEnd();
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }
    }
}